﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
using System.Xml;

namespace AppWatcher
{
    public partial class AppWatcher : ServiceBase
    {
        Thread m_Thread;

        public AppWatcher()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            m_Thread = new Thread(new ThreadStart(ThreadFun));
            m_Thread.IsBackground = true;
            m_Thread.Start();
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }

        void ThreadFun()
        {
            string applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            StreamWriter loger = new StreamWriter(Path.Combine(applicationBase, "AppWatcher.Log"), true, Encoding.GetEncoding("GB18030"));
            try
            {
                //string appPath = null;
                //XmlReader configXML = XmlReader.Create(Path.Combine(applicationBase, "AppWatcher.XML"));
                //while (configXML.Read())
                //{
                //    if (configXML.NodeType != XmlNodeType.Element || configXML.Name != "AppName")
                //        continue;

                //    while (configXML.Read())
                //    {
                //        if (configXML.NodeType == XmlNodeType.EndElement)
                //            break;

                //        if (configXML.NodeType == XmlNodeType.Text)
                //            appPath = configXML.Value;
                //    }
                //    break;
                //}
                //if (appPath == null)
                //    return;
                Config config = new Config(); ;
                string appPath = config.AppName;
                loger.WriteLine(string.Format("AppPath\t{0}", appPath));
                loger.Flush();

                bool writeLog = false;
                while (true)
                {
                    Process p = FindProcess(appPath);
                    if (p != null)
                    {
                        if (writeLog)
                        {
                            loger.WriteLine("{0} 程序成功启动 {1}", DateTime.Now, appPath);
                            writeLog = false;
                        }
                        Thread.Sleep(60 * 1000);                      

                        continue;
                    }

                    loger.WriteLine("{0} 程序没有运行 {1}", DateTime.Now, appPath);
                    loger.Flush();
                    
                    ProcessStartInfo exeinfo = new ProcessStartInfo();
                    exeinfo.FileName = appPath;
                    exeinfo.WorkingDirectory = Path.GetDirectoryName(appPath);

                    Process.Start(exeinfo);
                    writeLog = true;
                    Thread.Sleep(50000000);
                }
            }
            catch (Exception e)
            {
                loger.WriteLine(e.Message);
            }
            finally
            {
                loger.Close();
            }
        }

        Process FindProcess(string strName)
        {
            Process[] procs = Process.GetProcesses();
            foreach (Process p in procs)
            {
                try
                {
                    if (string.Compare(p.MainModule.FileName, strName, StringComparison.OrdinalIgnoreCase) == 0)
                        return p;
                }
                catch (System.ComponentModel.Win32Exception)
                {
                    continue;
                }
                catch (InvalidOperationException)
                {
                    continue;
                }
            }
            return null;
        }
    }
}
